package controllers;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.BeanUsers;
import models.User;
import utils.DAOUser;

/**
 * Servlet implementation class ContactsController
 */
public class ContactsController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ContactsController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String message = "";
		synchronized (session) {
			User currentUser = (User) session.getAttribute("currentUser");

			int numUsers = 5;
			if (request.getParameter("numUsers") != null)
				numUsers = Integer.parseInt(request.getParameter("numUsers"));
			else if (session.getAttribute("numUsers") != null)
				numUsers = (Integer) session.getAttribute("numUsers");

			try {
				BeanUsers beanUsers = new BeanUsers();
				DAOUser daouser = new DAOUser();

				beanUsers.setUsers(daouser.ContactUsers(currentUser.getUser(),
						numUsers));
				daouser.setFollowers(beanUsers.getUsers(),
						currentUser.getUser());
				daouser.setContacts(beanUsers.getUsers(), currentUser.getUser());

				request.setAttribute("beanUsers", beanUsers);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				message += "Ha habido un error al intentar recuperar los contactos";
			}
		}
		request.setAttribute("message", message);

		RequestDispatcher dispatcher = request
				.getRequestDispatcher("/users.jsp");
		if (dispatcher != null)
			dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
